/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.net.greenet.scheduler;

import cn.net.greenet.device.logic.DeviceManagementImpl;
import cn.net.greenet.device.logic.IDeviceManagement;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 获取DPI上报的JSON 转换JSON格式然后响应
 *
 * @author liangdelin
 */
public class SynPolicyChangeJson {

    public static String changeJson(String dpi_id, String json) {
        Map<String, String> instanceMap = getInstance(dpi_id);
        JSONObject jo = new JSONObject();  //return json
        jo.put("dpi_id", dpi_id);
        JSONArray jsonArr = new JSONArray();
        jo.put("data", jsonArr);
        jo.put("dpi_id", dpi_id);
        JSONObject joo = JSONObject.fromObject(json);  //get old json
        Set<String> key = joo.keySet();
        JSONObject njoo = null;
        JSONObject jooo = null;
        for (String k : key) {
            jooo = joo.getJSONObject(k);
            if (!"-1".equals(jooo.get("version"))) {
                njoo = new JSONObject();
                njoo.put("message_type", k);
                njoo.put("instance", instanceMap.get(k));
                njoo.put("dpi_edition", (int) jooo.get("version"));
                jsonArr.add(njoo);
            }
        }
        return jo.toString();
    }

    public static Map<String, String> getInstance(String id) {
        Map<String, String> dataMap = new HashMap<>();
        JSONArray jsonArr = null;
        if (id != null && id.matches("[0-9]*")) {
            IDeviceManagement iDeviceManagement = new DeviceManagementImpl();
            jsonArr = iDeviceManagement.getDevPolicyBankInfo(id);
            JSONObject jo = null;
            for (int i = 0; i < jsonArr.size(); i++) {
                jo = jsonArr.getJSONObject(i);
                dataMap.put(jo.getString("Message_Type"), jo.getString("strategy_name"));
            }
        }
        return dataMap;
    }
}
